<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=0">
    <meta name="generator" content="editplus"/>
    <style type="text/css">
        .content {
            color: #810404;
        }
        body, p {
            padding: 0;
            margin: 0;
        }
        .content-front {
            position: absolute;

            width: 100%;
            height: 680px;
        }
        .top_head {
            width: 100%;
            height: 24px;
            color: #fff;
            text-align: left;
            background: rgba(0, 0, 0, .5)
        }
        .mess_content {
            width: 95%;
            max-height: 680px;
            margin: 0 auto;
            padding-top: 10px;
        }
        .u p {
            width: 150px;
            font-size: 12px;
            position: absolute;
            top: -20px;
            color: #888;
        }
        .setBar_list p {
            width: 100%;
            height: 40px;
            line-height: 40px;
            text-align: center;
            border-bottom: 1px solid #B0E0E6;
        }
        .send_wrap {
            border: #dcdcdc 1px solid;
            display: flex;
            justify-content: space-between;
            flex-direction: row;
            width: 100%;
            height: auto;
            position: fixed;
            bottom: 0;
            left: 0;
            background: rgba(255, 255, 255, .4);
            padding-top: 8px;
        }
        .send_post_word {
            flex: 1;
        }
        .send_post_word input[type=text] {
            width: 100%;
            height: 30px;
            padding-left: 5%;
        }
        .pub {
            box-shadow: rgba(0, 0, 0, .5) 2px 2px 5px;
            width: 62px;
            height: 32px;
            line-height: 32px;
            font-weight: bold;
            text-align: center;
            margin-right: 15px;
            margin-bottom: 15px;
        }
        .emoji a {
            display: inline-block;
            width: 30px;
            height: 30px;
            margin: 5px 5px;
        }
        .emoji a img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
<div>
    <div class="content content-front">
        <div class="top_head">王明</div>
        <div class="mess_content" id="messageboxer">

        </div>
    </div>
</div>
</div>
<div class="send_wrap">
    <div class="send_post_word">
        <input type='text' id="msg" placeholder="约吗">
    </div>
    <div class="pub" onclick="send()">发送</div>
</div>
</body>
</html>
<script src="jquery-3.2.1.min.js"></script>
<script>
    var socketName = 'ws://127.0.0.1/websocket/',
        lockReconnect = false,
        socket = null;
    //判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址
    if ('WebSocket' in window) {
        connectSocket();
    } else {
        alert('Not support websocket')
    }

    //连接webSocket
    function connectSocket() {
        try {
            socket = new WebSocket(socketName);
            console.log(socket);
            initSocketEvent();
        } catch (e) {
            reconnect();
            console.warn('socket connect error:', e);
        }
    }

    //重连
    function reconnect() {
        if (lockReconnect) return;
        lockReconnect = true;
        setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
            connectSocket();
            lockReconnect = false;
        }, 100);
    }

    function initSocketEvent() {
        //连接发生错误的回调方法
        socket.onerror = function (e) {
            console.error("socket error:" + e);
            console.warn("socked connect close! try to connect again!" + new Date().toLocaleString());
            reconnect();
        };

        //连接成功建立的回调方法
        socket.onopen = function (event) {
            //socketOnOpen(event);
            setInterval(function () {
                console.info('ping');
                socket.send(JSON.stringify({
                    act: 'ping',
                    data: 'Hi Server, I am LayIM! Ping! Ping! Ping!'
                }))
            }, 30000);
            console.log("socket connect sucess:" + event);
        }

        //接收到消息的回调方法
        socket.onmessage = function (event) {
            socketOnMessage(event);
            //console.log("socket get a message:" + event.data);
        }

        //连接关闭的回调方法
        socket.onclose = function (e) {
            console.warn("socked connect close! try to connect again!" + new Date().toLocaleString());
            reconnect();
        }
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        socket.close();
    }

    //关闭连接
    function closeWebSocket() {
        socket.close();
    }

    var processMessageBox = function (data){
        $("#messageboxer").append("<p>："+JSON.stringify(data)+"</p>");
    };

    var socketOnMessage = function (evt) {
        var res = JSON.parse(evt.data);
        //console.log('OnMessage:',res);
        switch (res.act) {
            //使用clientId连接到服务之后
            case 'link':
                console.warn(res.data);
                socket.send(JSON.stringify({
                    act: 'bind',
                    token: '914050262118ss'
                }));
                break;
            case 'read':
                console.log(res.data);
                break;
            //收到绑定成功，即可通信聊天
            case 'bind':
                console.warn(res.data);
                break;
            //收到聊天消息
            case 'msg':
                if(res.data.system===false){
                    console.info(res.data);
                    socket.send(JSON.stringify({act: 'read', id: res.data.id}));
                }
                processMessageBox(res.data.content+'(来自：'+res.data.uid+')');
                break;
            //心跳
            case 'pong':
                //console.log(res.data);
                console.info('pong');
                break;
            //心跳
            case 'error':
                console.log(res.data);
                break;
        }
    };

</script>
